//
//  HBlackListVC.m
//  BXlive
//
//  Created by huangzhiwen on 2017/3/27.
//  Copyright © 2017年 cat. All rights reserved.
//

#import "HBlackListVC.h"
#import "HBlackListCell.h"
#import "HBlackListModel.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <Masonry/Masonry.h>

#import "ImSDK_Plus.h"

@interface HBlackListVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic,strong)UIView *navigationView;
@property (assign, nonatomic) NSInteger offset;

@end

@implementation HBlackListVC
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.title = @"黑名单";
    self.fd_prefersNavigationBarHidden = YES;
    [self.view setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    [self setupNavigationView];
    [self createTableView];
    [self createRessh];
    
}
-(void)setupNavigationView{
    _navigationView = [UIView new];
    [self.view addSubview:_navigationView];
    [_navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(__kTopAddHeight+64);
    }];
    [_navigationView setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    WS(weakSelf);
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:BtnTouchUpInside];
    [_navigationView addSubview:backBtn];
    [backBtn setImage:CImage(@"back_black") forState:BtnNormal];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"黑名单", nil) Font:SLBFont(__ScaleWidth(18)) TextColor:sl_textColors];
    label.textAlignment = 1;
    [_navigationView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(44);
        make.right.mas_equalTo(-44);
        make.centerY.equalTo(weakSelf.navigationView.mas_bottom).offset(-22);
        make.height.mas_equalTo(25);
    }];
}



-(void)createRessh{
    [self.mainTableView addHeaderWithTarget:self action:@selector(TableDragWithDown)];
    [self.mainTableView headerBeginRefreshing];
}
-(void)TableDragWithDown {
    _offset = 0;
    [self loadData];
}

- (void)loadMoreData {
    _offset = _dataArray.count;
    [self loadData];
}


-(void)loadData{
    [[NewHttpRequestHuang sharedNewHttpRequestHuang]BlacklistIndexWithOffset:[NSString stringWithFormat:@"%ld",(long)_offset] Success:^(id responseObject) {
        [self.mainTableView headerEndRefreshing];
        if ([responseObject[@"code"] intValue]==0) {
            if (!self.offset) {
                [self.dataArray removeAllObjects];
                self.mainTableView.isNoMoreData = NO;
            }
            NSMutableArray *dataArray =responseObject[@"data"];
            if (dataArray && dataArray.count) {
                for (NSDictionary *dic in dataArray) {
                    HBlackListModel *model = [HBlackListModel objectWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
            } else {
                self.mainTableView.isNoMoreData = YES;
            }
            [self.mainTableView reloadData];
        }
        self.mainTableView.isRefresh = NO;
        self.mainTableView.isNoNetwork = NO;
    } Failure:^(NSError *error) {
        [self.mainTableView headerEndRefreshing];
        self.mainTableView.isRefresh = NO;
        self.mainTableView.isNoNetwork = !error.isNetWorkConnectionAvailable;
    }];
}
- (void)createTableView
{
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight - 64 - __kTopAddHeight)];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.emptyDataSetSource = self;
    self.mainTableView.emptyDataSetDelegate = self;
    self.mainTableView.backgroundColor = [UIColor clearColor];
    self.mainTableView.showsVerticalScrollIndicator = YES;
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.estimatedRowHeight = 0;
    [self.view addSubview:self.mainTableView];
    WS(weakSelf);
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.equalTo(weakSelf.navigationView.mas_bottom);
    }];
}

- (void)deleteGoodsWithModel:(HBlackListModel*)model atIndexPath:(NSIndexPath *)indexPath {
    [[NewHttpRequestHuang sharedNewHttpRequestHuang] BlacklistDeleteWithUserId:[NSString stringWithFormat:@"%@",model.to_uid] Success:^(id responseObject) {
        if ([responseObject[@"code"] intValue]==0) {
            [self.dataArray removeObject:model];
            [self.mainTableView reloadData];
            
            [[V2TIMManager sharedInstance] deleteFromBlackList:@[[NSString stringWithFormat:@"%@",model.to_uid]] succ:^(NSArray<V2TIMFriendOperationResult *> *resultList) {
                NSLog(@"移出黑名单成功");
            } fail:^(int code, NSString *desc) {
                NSLog(@"移出黑名单失败");

            }];
            
//            [[NIMSDK sharedSDK].userManager removeFromBlackBlackList:[NSString stringWithFormat:@"%@",model.to_uid] completion:^(NSError * _Nullable error) {
//
//            }];
        }else{
            [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
        }
    } Failure:^(NSError *error) {
        
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma - mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return __ScaleWidth(48*2);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HBlackListCell *cell = [HBlackListCell cellWithTabelView:tableView];
    cell.model = self.dataArray[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    WS(ws);
    cell.btnClick = ^(UITableViewCell *cell) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"您确认要移除该人员吗?", nil)  preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [ws deleteGoodsWithModel:ws.dataArray[indexPath.row] atIndexPath:indexPath];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cancelAction];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    };
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint point =  [scrollView.panGestureRecognizer translationInView:self.view];
    if (point.y > 0 ) {
        return;
    }
    if (scrollView.contentOffset.y <= 0) {
        return;
    }
    if (scrollView.contentOffset.y + scrollView.frame.size.height + kFooterRefreshSpace > scrollView.contentSize.height) {
        if (scrollView.isNoMoreData || scrollView.isNoNetwork) {
            return;
        }
        if (!scrollView.isRefresh) {
            scrollView.isRefresh = YES;
            [self loadMoreData];
        }
    }
}

#pragma - mark DZNEmptyDataSetSource
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if ([NewHttpManager isNetWorkConnectionAvailable]) {
        return nil;
    } else {
        WS(ws);
        BXNoNetworkView *noNetworkView = [[BXNoNetworkView alloc]initWithHeight:290];
        noNetworkView.needRefresh = ^{
            [ws TableDragWithDown];
        };
        return noNetworkView;
    }
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"空页面状态"];
    
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = NSLocalizedString(@"这里还没有内容哦~", nil);
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    [attributes setObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];
    [attributes setObject:MinorColor forKey:NSForegroundColorAttributeName];
    [attributes setValue:paragraph forKey:NSParagraphStyleAttributeName];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
    return attributeString;
}


#pragma - mark DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

@end
